package org.aynu.userservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.aynu.cartservice.common.CartResponse;
import org.aynu.userservice.common.Constants;
import org.aynu.userservice.common.UserResponse;
import org.aynu.userservice.feign.CartServiceClient;
import org.aynu.userservice.mapper.UserMapper;
import org.aynu.userservice.mapper.VisitorMapper;
import org.aynu.userservice.model.User;
import org.aynu.userservice.model.Visitor;
import org.aynu.userservice.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.sql.Timestamp;
import java.sql.Wrapper;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 用户服务实现
 *
 * @author 小粥
 * @since 2025/03/02
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private final UserMapper userMapper;
    private final CartServiceClient cartServiceClient;
    private final VisitorMapper visitorMapper;

    private static final Pattern EMAIL_PATTERN = Pattern.compile("^[\\w-.]+@([\\w-]+\\.)+[\\w-]{2,4}$");
    private static final Pattern PHONE_PATTERN = Pattern.compile("^1[3-9]\\d{9}$");

    @Autowired
    public UserServiceImpl(UserMapper userMapper, CartServiceClient cartServiceClient, VisitorMapper visitorMapper) {
        this.userMapper = userMapper;
        this.cartServiceClient = cartServiceClient;
        this.visitorMapper = visitorMapper;
    }

    // ----------------------- UserService Methods -----------------------

    private void validateUser(User user) {
        if (user == null) {
            throw new IllegalArgumentException("用户信息不能为空");
        }
        if (!StringUtils.hasText(user.getUsername())) {
            throw new IllegalArgumentException("用户名不能为空");
        }
        if (!StringUtils.hasText(user.getEmail()) || !EMAIL_PATTERN.matcher(user.getEmail()).matches()) {
            throw new IllegalArgumentException("邮箱格式不正确");
        }
        if (!StringUtils.hasText(user.getPasswordHash())) {
            throw new IllegalArgumentException("密码不能为空");
        }
    }

    // 修改 findUserByUsername 方法
    private User findUserByUsername(String username) {
        return userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, username)
                .eq(User::getIsDeleted, 0));
    }

    private User findUserByUsernameAndEmail(String username, String email) {
        return userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, username)
                .eq(User::getEmail, email));
    }

    @Override
    public User findUserByNameOrPhone(String nameOrPhone) {
        if (!StringUtils.hasText(nameOrPhone)) {
            return null;
        }
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        if (PHONE_PATTERN.matcher(nameOrPhone).matches()) {
            queryWrapper.eq(User::getPhoneNumber, nameOrPhone);
        } else {
            queryWrapper.eq(User::getUsername, nameOrPhone);
        }
        queryWrapper.eq(User::getIsDeleted, 0);
        return userMapper.selectOne(queryWrapper);
    }

    @Override
    public UserResponse<String> register(User user) {
        try {
            validateUser(user);

            // 查找用户名是否存在且未被删除
            User existingUser = findUserByUsername(user.getUsername());
            if (existingUser != null && existingUser.getIsDeleted() == 0) {
                return UserResponse.error(Constants.USER_EXISTS);
            }

            user.setCreatedAt(new Timestamp(System.currentTimeMillis()));
            user.setIsDeleted(0);
            int result1 = userMapper.insert(user);
            if (result1 == 0) {
                return UserResponse.error(Constants.REGISTER_FAILED);
            }

            Map<String, Object> map = Map.of("userId", user.getUserId());
            CartResponse<Integer> result2 = cartServiceClient.createCart(map);
            if (result2 == null || result2.getData() == null) {
                throw new RuntimeException(Constants.CART_CREATE_FAILED);
            }

            return UserResponse.success(Constants.REGISTER_SUCCESS);
        } catch (IllegalArgumentException e) {
            log.warn("用户注册失败：{}", e.getMessage());
            return UserResponse.error(e.getMessage());
        } catch (Exception e) {
            log.error("用户注册异常：{}", e.getMessage(), e);
            throw new RuntimeException(Constants.REGISTER_FAILED, e);
        }
    }

    @Override
    public UserResponse<Map<String, Object>> login(User userEntity) {
        try {
            if (userEntity == null || !StringUtils.hasText(userEntity.getUsername()) || !StringUtils.hasText(userEntity.getPasswordHash())) {
                return UserResponse.error("用户名或密码不能为空");
            }
            User user = lambdaQuery()
                    .eq(User::getUsername, userEntity.getUsername())
                    .eq(User::getPasswordHash, userEntity.getPasswordHash())
                    .eq(User::getIsDeleted, 0)
                    .one();
            if (user == null) {
                return UserResponse.error(Constants.USERNAME_OR_PASSWORD_ERROR);
            }
            Map<String, Object> cartRequest = Map.of("userId", user.getUserId());
            CartResponse<Integer> cartResponse = cartServiceClient.selectCartId(cartRequest);
            if (cartResponse == null || cartResponse.getData() == null) {
                return UserResponse.error(Constants.CART_QUERY_FAILED);
            }
            Map<String, Object> result = Map.of(
                    "user", user,
                    "cartId", cartResponse.getData()
            );
            return UserResponse.success(result);
        } catch (Exception e) {
            log.error("用户登录异常：{}", e.getMessage(), e);
            return UserResponse.error(Constants.SERVER_ERROR + e.getMessage());
        }
    }

    @Override
    public UserResponse<Integer> updateUser(User userEntity) {
        try {
            if (userEntity.getUserId() == null) {
                return UserResponse.error("用户ID不能为空");
            }
            boolean result = lambdaUpdate()
                    .eq(User::getUserId, userEntity.getUserId())
                    .set(User::getEmail, userEntity.getEmail())
                    .set(User::getPhoneNumber, userEntity.getPhoneNumber())
                    .set(User::getUpdatedAt, new Timestamp(System.currentTimeMillis()))
                    .update();
            return result ? UserResponse.success(Constants.USER_UPDATE_SUCCESS, userEntity.getUserId())
                    : UserResponse.error(Constants.USER_UPDATE_FAILED);
        } catch (IllegalArgumentException e) {
            log.warn("用户信息更新失败：{}", e.getMessage());
            return UserResponse.error(e.getMessage());
        } catch (Exception e) {
            log.error("更新用户信息异常：{}", e.getMessage(), e);
            return UserResponse.error(Constants.SERVER_ERROR + e.getMessage());
        }
    }

    @Override
    public UserResponse<String> resetPassword(String username, String email, String newPassword) {
        try {
            if (!StringUtils.hasText(newPassword)) {
                return UserResponse.error("新密码不能为空");
            }
            User user = findUserByUsernameAndEmail(username, email);
            if (user == null || user.getIsDeleted() == 1) {
                return UserResponse.error(Constants.USERNAME_OR_EMAIL_ERROR);
            }
            user.setPasswordHash(newPassword);
            user.setUpdatedAt(new Timestamp(System.currentTimeMillis()));
            boolean result = updateById(user);
            return result ? UserResponse.success(Constants.PASSWORD_RESET_SUCCESS)
                    : UserResponse.error(Constants.PASSWORD_RESET_FAILED);
        } catch (Exception e) {
            log.error("重置密码异常：{}", e.getMessage(), e);
            return UserResponse.error(Constants.SERVER_ERROR + e.getMessage());
        }
    }

    @Override
    public UserResponse<Map<String, Object>> getAllUsers(int pageNum, int pageSize) {
        try {
            Page<User> page = new Page<>(pageNum, pageSize);
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getIsDeleted, 0);
            page = userMapper.selectPage(page, queryWrapper);
            Map<String, Object> result = new HashMap<>();
            result.put("total", page.getTotal());
            result.put("users", page.getRecords());
            return UserResponse.success(Constants.QUERY_SUCCESS, result);
        } catch (Exception e) {
            log.error("分页查询用户异常：{}", e.getMessage(), e);
            return UserResponse.error(Constants.SERVER_ERROR + e.getMessage());
        }
    }

    @Override
    public UserResponse<Integer> createUser(User user) {
        try {
            validateUser(user);
            if (findUserByUsername(user.getUsername()) != null) {
                return UserResponse.error(Constants.USER_EXISTS);
            }
            user.setCreatedAt(new Timestamp(System.currentTimeMillis()));
            user.setRole("resident");
            user.setIsDeleted(0);
            int result = userMapper.insert(user);
            return result > 0 ? UserResponse.success(Constants.CREATE_USER_SUCCESS, user.getUserId())
                    : UserResponse.error(Constants.CREATE_USER_FAILED);
        } catch (IllegalArgumentException e) {
            log.warn("创建用户失败：{}", e.getMessage());
            return UserResponse.error(e.getMessage());
        } catch (Exception e) {
            log.error("创建用户异常：{}", e.getMessage(), e);
            return UserResponse.error(Constants.SERVER_ERROR + e.getMessage());
        }
    }

    @Override
    public UserResponse<Boolean> updateUserByAdmin(User user) {
        try {
            validateUser(user);
            if (user.getUserId() == null) {
                return UserResponse.error("用户ID不能为空");
            }
            UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("user_id", user.getUserId());
            boolean hasUpdate = false;
            if (StringUtils.hasText(user.getUsername())) {
                updateWrapper.set("username", user.getUsername());
                hasUpdate = true;
            }
            if (StringUtils.hasText(user.getPasswordHash())) {
                updateWrapper.set("password_hash", user.getPasswordHash());
                hasUpdate = true;
            }
            if (StringUtils.hasText(user.getEmail())) {
                updateWrapper.set("email", user.getEmail());
                hasUpdate = true;
            }
            if (StringUtils.hasText(user.getPhoneNumber())) {
                updateWrapper.set("phone_number", user.getPhoneNumber());
                hasUpdate = true;
            }
            updateWrapper.set("updated_at", new Timestamp(System.currentTimeMillis()));
            if (!hasUpdate) {
                return UserResponse.error("没有需要更新的字段");
            }
            boolean result = update(null, updateWrapper);
            return result ? UserResponse.success(Constants.USER_UPDATE_SUCCESS, true)
                    : UserResponse.error(Constants.USER_UPDATE_FAILED);
        } catch (IllegalArgumentException e) {
            log.warn("更新用户信息失败：{}", e.getMessage());
            return UserResponse.error(e.getMessage());
        } catch (Exception e) {
            log.error("更新用户信息异常：{}", e.getMessage(), e);
            return UserResponse.error(Constants.SERVER_ERROR + e.getMessage());
        }
    }

    @Override
    public UserResponse<Boolean> deleteUser(int userId) {
        try {
            boolean result = lambdaUpdate()
                    .eq(User::getUserId, userId)
                    .set(User::getIsDeleted, 1)
                    .set(User::getUpdatedAt, new Timestamp(System.currentTimeMillis()))
                    .update();
            return result ? UserResponse.success(Constants.DELETE_USER_SUCCESS, true)
                    : UserResponse.error(Constants.DELETE_USER_FAILED);
        } catch (Exception e) {
            log.error("删除用户异常：{}", e.getMessage(), e);
            return UserResponse.error(Constants.SERVER_ERROR + e.getMessage());
        }
    }

    @Override
    public UserResponse<Integer> createAdmin(User admin) {
        try {
            admin.setRole("admin");
            validateUser(admin);
            if (findUserByUsername(admin.getUsername()) != null) {
                return UserResponse.error(Constants.ADMIN_USERNAME_EXISTS);
            }
            admin.setCreatedAt(new Timestamp(System.currentTimeMillis()));
            admin.setIsDeleted(0);
            int result = userMapper.insert(admin);
            return result > 0 ? UserResponse.success(Constants.CREATE_ADMIN_SUCCESS, admin.getUserId())
                    : UserResponse.error(Constants.CREATE_ADMIN_FAILED);
        } catch (IllegalArgumentException e) {
            log.warn("创建管理员失败：{}", e.getMessage());
            return UserResponse.error(e.getMessage());
        } catch (Exception e) {
            log.error("创建管理员异常：{}", e.getMessage(), e);
            return UserResponse.error(Constants.SERVER_ERROR + e.getMessage());
        }
    }


    // ----------------------- Visitor Methods -----------------------

    private void validateVisitor(Visitor visitor) {
        if (visitor == null) {
            throw new IllegalArgumentException("访客信息不能为空");
        }
        if (!StringUtils.hasText(visitor.getName())) {
            throw new IllegalArgumentException("访客姓名不能为空");
        }
        if (!StringUtils.hasText(visitor.getPhoneNumber()) || !PHONE_PATTERN.matcher(visitor.getPhoneNumber()).matches()) {
            throw new IllegalArgumentException("电话号码格式不正确");
        }
        if (!StringUtils.hasText(visitor.getPurpose())) {
            throw new IllegalArgumentException("访问目的不能为空");
        }
    }

    @Override
    public UserResponse<Integer> registerVisitor(Visitor visitor, String residentNameOrPhone) {
        try {
            validateVisitor(visitor);
            if (!StringUtils.hasText(residentNameOrPhone)) {
                return UserResponse.error(Constants.RESIDENT_NAME_OR_PHONE_REQUIRED);
            }
            User resident = findUserByNameOrPhone(residentNameOrPhone);
            if (resident == null) {
                return UserResponse.error(Constants.RESIDENT_NOT_FOUND);
            }
            visitor.setUserId(resident.getUserId());
            visitor.setApprovalStatus("PENDING");
            visitor.setCreatedAt(new Timestamp(System.currentTimeMillis()));
            visitor.setUpdatedAt(new Timestamp(System.currentTimeMillis()));
            visitor.setIsDeleted(0);
            int result = visitorMapper.insert(visitor);
            if (result == 0) {
                return UserResponse.error(Constants.VISITOR_REGISTER_FAILED);
            }
            return UserResponse.success(Constants.VISITOR_REGISTER_SUCCESS, visitor.getVisitorId());
        } catch (IllegalArgumentException e) {
            log.warn("访客登记失败：{}", e.getMessage());
            return UserResponse.error(e.getMessage());
        } catch (Exception e) {
            log.error("访客登记异常：{}", e.getMessage(), e);
            return UserResponse.error(Constants.SERVER_ERROR + e.getMessage());
        }
    }

    @Override
    public UserResponse<String> approveVisitor(Integer visitorId, String status) {
        try {
            if (visitorId == null || visitorId <= 0) {
                return UserResponse.error(Constants.VISITOR_ID_INVALID);
            }
            if (status == null || (!status.equals("APPROVED") && !status.equals("REJECTED"))) {
                return UserResponse.error(Constants.STATUS_INVALID);
            }
            Visitor visitor = visitorMapper.selectOne(new LambdaQueryWrapper<Visitor>()
                    .eq(Visitor::getVisitorId, visitorId)
                    .eq(Visitor::getIsDeleted, 0));
            if (visitor == null) {
                return UserResponse.error(Constants.VISITOR_NOT_FOUND);
            }
            LambdaUpdateWrapper<Visitor> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(Visitor::getVisitorId, visitorId)
                    .set(Visitor::getApprovalStatus, status)
                    .set(Visitor::getUpdatedAt, new Timestamp(System.currentTimeMillis()));
            boolean result = visitorMapper.update(null, updateWrapper) > 0;
            return result ? UserResponse.success(Constants.VISITOR_APPROVE_SUCCESS)
                    : UserResponse.error(Constants.VISITOR_APPROVE_FAILED);
        } catch (Exception e) {
            log.error("审批访客异常：{}", e.getMessage(), e);
            return UserResponse.error(Constants.SERVER_ERROR + e.getMessage());
        }
    }

    @Override
    public UserResponse<Map<String, Object>> getAllVisitors(int pageNum, int pageSize) {
        try {
            Page<Visitor> page = new Page<>(pageNum, pageSize);
            LambdaQueryWrapper<Visitor> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Visitor::getIsDeleted, 0);
            page = visitorMapper.selectPage(page, queryWrapper);
            Map<String, Object> result = new HashMap<>();
            result.put("total", page.getTotal());
            result.put("visitors", page.getRecords());
            return UserResponse.success(Constants.QUERY_SUCCESS, result);
        } catch (Exception e) {
            log.error("查询所有访客异常：{}", e.getMessage(), e);
            return UserResponse.error(Constants.SERVER_ERROR + e.getMessage());
        }
    }

    @Override
    public UserResponse<Map<String, Object>> getVisitorsByUserId(Integer userId, int pageNum, int pageSize) {
        try {
            if (userId == null || userId <= 0) {
                return UserResponse.error(Constants.USER_ID_INVALID);
            }
            Page<Visitor> page = new Page<>(pageNum, pageSize);
            LambdaQueryWrapper<Visitor> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Visitor::getUserId, userId)
                    .eq(Visitor::getIsDeleted, 0);
            page = visitorMapper.selectPage(page, queryWrapper);
            Map<String, Object> result = new HashMap<>();
            result.put("total", page.getTotal());
            result.put("visitors", page.getRecords());
            return UserResponse.success(Constants.QUERY_SUCCESS, result);
        } catch (Exception e) {
            log.error("查询用户访客异常：{}", e.getMessage(), e);
            return UserResponse.error(Constants.SERVER_ERROR + e.getMessage());
        }
    }

    @Override
    public UserResponse<String> deleteVisitor(Integer visitorId) {
        try {
            if (visitorId == null || visitorId <= 0) {
                return UserResponse.error(Constants.VISITOR_ID_INVALID);
            }
            LambdaUpdateWrapper<Visitor> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(Visitor::getVisitorId, visitorId)
                    .set(Visitor::getIsDeleted, 1)
                    .set(Visitor::getUpdatedAt, new Timestamp(System.currentTimeMillis()));
            boolean result = visitorMapper.update(null, updateWrapper) > 0;
            return result ? UserResponse.success(Constants.VISITOR_DELETE_SUCCESS)
                    : UserResponse.error(Constants.VISITOR_DELETE_FAILED);
        } catch (Exception e) {
            log.error("删除访客异常：{}", e.getMessage(), e);
            return UserResponse.error(Constants.SERVER_ERROR + e.getMessage());
        }
    }


    /**
     * @param userId
     * @return {@link UserResponse }<{@link User }>
     * @author 小粥
     * @since 2025/03/05
     */

    @Override
    public UserResponse<User> selectResident(Integer userId) {
        log.info("收到查询用户请求，用户Id：{}", userId);
        User user = baseMapper.selectById(userId);
        if (user == null) {
            return UserResponse.error(Constants.USER_NOT_FOUND);
        }
        return UserResponse.success(user);
    }

    /**
     * 获取前五条用户数据
     *
     * @return 用户列表响应
     */
    @Override
    public UserResponse<Map<String, Object>> getFiveUsers() {
        try {
            // 构建查询条件
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getIsDeleted, 0);

            // 执行查询
            List<User> userList = userMapper.selectList(queryWrapper);

            // 截取前 5 条记录
            int endIndex = Math.min(userList.size(), 5);
            List<User> topFiveUsers = userList.subList(0, endIndex);

            // 封装查询结果
            Map<String, Object> result = new HashMap<>();
            result.put("total", topFiveUsers.size());
            result.put("users", topFiveUsers);

            return UserResponse.success("查询成功", result);
        } catch (Exception e) {
            log.error("获取前五条用户数据异常：{}", e.getMessage(), e);
            return UserResponse.error("服务器异常：" + e.getMessage());
        }
    }

    /*获取用户总数量*/
    @Override
    public UserResponse<Integer> getUserCount() {
        try {
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getIsDeleted, 0);
            Integer count = Math.toIntExact(userMapper.selectCount(queryWrapper));
            return UserResponse.success(count);
        } catch (Exception e) {
            log.error("获取用户总数量异常：{}", e.getMessage(), e);
            return UserResponse.error(Constants.SERVER_ERROR + e.getMessage());
        }
    }

    @Override
public UserResponse<Map<String, Object>> selectAllUserId() {
    try {
        // 构建查询条件：只选择userId字段且未删除的用户
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(User::getUserId)
                    .eq(User::getIsDeleted, 0);

        // 执行查询获取所有用户ID列表
        List<Integer> userIds = userMapper.selectObjs(queryWrapper).stream()
            .map(Integer.class::cast)
            .collect(Collectors.toList());

        // 封装结果
        Map<String, Object> result = new HashMap<>();
        result.put("userIds", userIds);

        return UserResponse.success("查询成功", result);
    } catch (Exception e) {
        log.error("查询所有用户ID异常：{}", e.getMessage(), e);
        return UserResponse.error("服务器异常：" + e.getMessage());
    }
}

/*获取用户所有信息*/
    @Override
    public UserResponse<List<User>> selectAllUser() {
        try {
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getIsDeleted, 0);
            List<User> users = userMapper.selectList(queryWrapper);
            return UserResponse.success(users);
        } catch (Exception e) {
            log.error("获取用户所有信息异常：{}", e.getMessage(), e);
            return UserResponse.error(Constants.SERVER_ERROR + e.getMessage());
        }
    }


  @Override
public UserResponse<List<Visitor>> queryVisitorByPhone(String phoneNumber) {
    try {
        // 参数校验：手机号不能为空且格式正确
        if (!StringUtils.hasText(phoneNumber)) {
            return UserResponse.error(Constants.PHONE_NUMBER_EMPTY);
        }
        if (!PHONE_PATTERN.matcher(phoneNumber).matches()) {
            return UserResponse.error(Constants.PHONE_FORMAT_ERROR);
        }

        // 构建查询条件：查询未删除且手机号匹配的访客
        LambdaQueryWrapper<Visitor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Visitor::getPhoneNumber, phoneNumber)
                    .eq(Visitor::getIsDeleted, 0);

        // 执行查询并获取列表
        List<Visitor> visitors = visitorMapper.selectList(queryWrapper);

        if (visitors.isEmpty()) {
            return UserResponse.error(Constants.VISITOR_NOT_FOUND);
        }

        return UserResponse.success(Constants.QUERY_SUCCESS, visitors);
    } catch (Exception e) {
        log.error("查询访客信息异常：{}", e.getMessage(), e);
        return UserResponse.error(Constants.SERVER_ERROR + e.getMessage());
    }
}



}